import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router } from '@angular/router';
import { defalutImg } from 'src/app/comm';
import { DatePipe } from '@angular/common';

import { LoveRecycManageService } from '../love-recyc-manage.service';

@Component({
  selector: 'app-love-brand-config',
  templateUrl: './love-brand-config.component.html',
  styleUrls: ['./love-brand-config.component.scss'],
  providers: [DatePipe]
})
export class LoveBrandConfigComponent implements OnInit {
  
  fallback: string = defalutImg;

  seachParams: any = {
    name: '',
    beginTime: '',
    endTime: ''
  };
  updateTimes: any = [];

  tableData: any = [];
  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };

  // modal
  validateForm!: FormGroup;
  isVisible: boolean = false;
  modalType: number = 0; // 0：新增，1：编辑
  modalItem: any = {};
  subModalLoding: boolean = false;
  uploadLoading: boolean = false;

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private datePipe: DatePipe,
    private router: Router,
    private services: LoveRecycManageService
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      name: ['', [Validators.required]],
      alias: [''],
      url: ['', [Validators.required]]
    });
    this.loadTable();
  }

  async loadTable() {
    try {
      let params: any = {
        ...this.seachParams,
        page: this.tableParams.page,
        pageSize: this.tableParams.pageSize
      }
      this.tableParams.tableLoading = true;
      const res: any = await this.services.getRecycleBrandList(params);
      this.tableParams.tableLoading = false;

      if (res.code == 0) {
        const { records, total } = res.data || {};
        this.tableData = records || [];
        this.tableParams.total = total || 0;
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  seachData() {
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData() {
    for (let key in this.seachParams) {
      this.seachParams[key] = '';
    }
    this.updateTimes = [];

    this.tableParams.page = 1;
    this.loadTable();
  }

  // 更新时间change
  timeChange(result: Date[]) {
    this.seachParams.beginTime = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
    this.seachParams.endTime = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
  }

  /**
   * 新增、编辑
   * @param num 0：新增，1：编辑
   * @param item 
   */
  showModal(num: number, item?: any) {
    if (num == 1) {
      this.modalItem = item;
      this.validateForm.patchValue({
        name: item.name,
        alias: item.alias,
        url: item.url
      });
    }
    this.modalType = num;
    this.isVisible = true;
  }

  handleCancel(): void {
    this.isVisible = false;
    this.validateForm.reset();
  }

  // 删除
  async deleteItem(item: any) {
    try {
      let params = {
        id: item.id,
        status: 2, // 0-禁用 1-启用 2-删除
      }
      const res: any = await this.services.updateRecycleBrandItem(params);
      if (res.code == 0) {
        this.message.success('删除成功');
        this.loadTable();
      } else {
        this.message.error(res.message || '删除失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // modal submit
  submitForm(): void {
    if (this.validateForm.valid) {
      this.subFormInterface();
      this.isVisible = false;
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
  async subFormInterface() {
    try {
      let params: any = {
        ...this.validateForm.value
      }
      let res: any = null;

      this.subModalLoding = true;
      if (this.modalType == 0) {
        res = await this.services.saveRecycleBrandItem(params);
      } else {
        params.id = this.modalItem.id;
        res = await this.services.updateRecycleBrandItem(params);
      }
      this.subModalLoding = false;

      if (res.code == 0) {
        this.message.success('操作成功');
        this.validateForm.reset();
        this.isVisible = false;
        this.loadTable();
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // 页数改变时的回调函数
  onPageSizeChange(sizeNum: number) {
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 图片上传
  onModalPreview(ev: any) {
    const { originFileObj }: any = ev?.file;
    this.uploadInterface(originFileObj);
  }
  // uploadInterface
  async uploadInterface(file: any) {
    if (!file || this.uploadLoading) {
      return
    }
    try {
      this.uploadLoading = true;
      const res: any = await this.services.uploadFileData(file)
      this.uploadLoading = false;

      if (res.code == 0) {
        this.message.success('图片上传成功');
        this.validateForm.get('url')?.setValue(res.data);
      } else {
        this.message.error(res.message || '图片上传失败');
      }
    } catch (error: any) {
      this.uploadLoading = false;
      this.validateForm.get('url')?.setValue('');
      this.message.error(error || '图片上传失败');
    }
  }
}
